<template>
    <div>
        <el-card class="operate-container" shadow="never">
            <div style="display: flex;height: 30px;">
                <el-button size="mini" class="btn-add" @click="fourthAdd()" >新增目的地</el-button>
                <el-button v-if="!isOneS && isCountry" size="mini" class="btn-add" @click="handleSort()" >排序</el-button>
                <el-button v-if="isOneS" size="mini" class="btn-add" @click="handleSortC()" >取消</el-button>
                <el-button style="background-color: #4099ef;color: #fff;" v-if="isOneS" size="mini" class="btn-add" @click="handleSortS()" >提交</el-button>
                <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
                    <el-form-item label="所属国家：">
                        <el-select v-model="listQuery.countryEsId" clearable
                            filterable
                            remote
                            :remote-method="queryCountry"
                            placeholder="请搜索"  >
                            <el-option
                                v-for="item in thirdOptions"
                                :key="item.id"
                                :label="item.cn + ' | ' + item.zhHant"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属目的地：">
                        <el-select v-model="listQuery.cityEsId" clearable
                            filterable
                            remote
                            :remote-method="queryCityd"
                            placeholder="请搜索"  >
                            <el-option
                                v-for="item in fourthOptions"
                                :key="item.id"
                                :label="item.cn ? item.cn + ' | ' + item.zhHant + ' | ' + item.country.cn : item.name + ' | ' + item.country.cn"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-button
                    style="float:right"
                    type="primary"
                    @click="handleSearchList()"
                    size="small">
                    查询搜索
                </el-button>
                <el-button
                    style="float:right;margin-right: 15px"
                    @click="handleResetSearch()"
                    size="small">
                    重置
                </el-button>
            </div>
            <span class="btn-list" @click="refBtn(4)">刷新列表</span>
        </el-card>
        <div class="table-container">
            <el-table ref="fourthTable"
                        :data="targetList"
                        row-key="id"
                        v-loading="listLoading"
                        style="width: 100%;"
                            border>
                <el-table-column label="拖拽排序" align="center">
                    <template slot="header">
                        拖拽排序
                        <!-- <el-button v-if="!isOneS" size="mini" class="btn-add" @click="handleSort()" >排序</el-button>
                        <el-button v-if="isOneS" size="mini" class="btn-add" @click="handleSortC()" >取消</el-button>
                        <el-button v-if="isOneS" size="mini" class="btn-add" @click="handleSortS()" >提交</el-button> -->
                    </template>
                    <template slot-scope="scope">
                        <i class="el-icon-s-operation"></i>
                    </template>
                </el-table-column>
                <el-table-column label="目的地推荐顺序" align="center">
                    <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="城市ID" align="center">
                    <template slot-scope="scope">{{scope.row.city.id}}</template>
                </el-table-column>
                <el-table-column label="目的地名称（简体|繁体）" align="center">
                    <template slot-scope="scope">{{scope.row.city.cn ? scope.row.city.cn : scope.row.city.name}} {{ scope.row.city.cn ? '|' : '' }} {{scope.row.city.zhHant}}
                        {{ scope.row.city.cn ? '|' : '' }} {{ scope.row.city.cn ? scope.row.city.name : '' }}
                    </template>
                </el-table-column>
                <el-table-column label="所属国家（简体|繁体）" align="center">
                    <template slot-scope="scope">{{scope.row.country.cn}} | {{scope.row.country.zhHant}}</template>
                </el-table-column>
                <el-table-column label="所属分组（简体|繁体）" align="center">
                    <template slot-scope="scope">{{scope.row.destinationGroup ? scope.row.destinationGroup.destinationGroupNameZh : null}} | {{scope.row.destinationGroup ? scope.row.destinationGroup.destinationGroupNameHk : null}}</template>
                </el-table-column>
                <el-table-column label="状态" align="center">
                    <template slot-scope="scope">
                        {{scope.row.status ? '显示' : '隐藏'}}
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" width="160" lign="center">
                    <template slot-scope="scope">{{scope.row.updateTime}}</template>
                </el-table-column>
                <el-table-column label="操作" width="360" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini"
                                type="text"
                                @click="fourthEdite(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button size="mini"
                                type="text"
                                @click="fourthDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog
            :title="'新增/编辑'"
            :visible.sync="fourthVisible"
            width="55%">
            <el-form :model="fourthResource"
                    ref="fourthForm"
                    :rules="rules"
                    label-width="150px" size="small">
                <el-form-item label="目的地：" prop="cityEsId">
                    <el-select v-model="fourthResource.cityEsId" clearable
                        filterable
                        remote
                        :remote-method="queryCityd"
                         placeholder="请搜索"  >
                        <el-option
                        v-for="item in fourthOptions"
                            :key="item.id"
                            :label="item.cn ? item.cn + ' | ' + item.zhHant + ' | ' + item.country.cn : item.name + ' | ' + item.country.cn"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态：" prop="status">
                    <el-radio-group v-model="fourthResource.status">
                        <el-radio :label="1">显示</el-radio>
                        <el-radio :label="0">隐藏</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="fourthVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="fourthDialogConfirm('fourthForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {  cityList,  destinationList,
        destinationDelete, destinationAdd, destinationUpdate, destinationSort, countryQuer } from '@/api/app';
import Sortable from 'sortablejs';
const defaultListQuery = {
    countryEsId: null,
    cityEsId: null,
};
export default {
    name: 'DestinationPage',
    data() {
        return {
            rules: {
                cityEsId: [
                    { required: true, message: '请选择目的地' }
                ],
                status: [
                    { required: true, message: '请选择状态' }
                ],
            },
            isCountry: false,
            listQuery: Object.assign({}, defaultListQuery),
            isOneS: false,
            targetList: [],
            thirdOptions: [],
            listLei: [],
            fourthVisible: false,
            fourthResource: {
                id: null,
                countryEsId: null,
                cityEsId: null,
                status: 1,
                sort: null,
                updateTime: null,
                createTime: null,
                deleteYn: null,
            },
            fourthOptions: [],
            isEdit: false,
            sortBoList: [],
            cityFirst: null,
            listLoading: false,
            sortShow: null,
        }
    },
    mounted() {
        // this.$nextTick(() => {
        //     const el = this.$el.querySelector('.el-table__body-wrapper tbody');
        //     Sortable.create(el, {
        //         onEnd: (event) => {
        //             const { oldIndex, newIndex } = event;
        //             this.rowDrop(oldIndex, newIndex);
        //         }
        //     })
        // });
    },
    watch: {
        // isCountry(newVal, oldVal) {
        //     if (newVal) {
        //         this.$nextTick(() => {
        //             const el = this.$el.querySelector('.el-table__body-wrapper tbody');
        //             Sortable.create(el, {
        //                 onEnd: (event) => {
        //                     const { oldIndex, newIndex } = event;
        //                     this.rowDrop(oldIndex, newIndex);
        //                 }
        //             })
        //         });
        //     } else {
        //         _this.rootDepart.sortableObj.destroy();
        //     }
        // }
    },
    created() {
        // this.fourthList();
        countryQuer({keyword: '中国'}).then(res => {
            this.thirdOptions = res.data;
            this.thirdOptions.forEach(item => {
                if (item.cn === '中国') {
                    this.listQuery.countryEsId = item.id;
                    this.cityFirst = item.id;
                    this.isCountry = true;
                }
            });
            this.fourthList();
        });
    },
    methods: {
        rowDrop(oldIndex, newIndex) {
            this.isOneS = true;
            const movedItem = this.targetList.splice(oldIndex, 1)[0];
            this.targetList.splice(newIndex, 0, movedItem);
            // const timeOld = this.targetList[oldIndex].sort;
            // const timeNew = this.targetList[newIndex].sort;
            // this.targetList[oldIndex].sort = timeNew;
            // this.targetList[newIndex].sort = timeOld;
        },
        queryCountry(key) {
            if (key) {
                countryQuer({keyword: key}).then(res => {
                    this.thirdOptions = res.data;
                });
            }
        },
        queryCityd(key) {
            if (key) {
                cityList({keyword: key}).then(res => {
                    this.fourthOptions = res.data;
                });
            }
        },
        fourthList() {
            this.listLoading = true;
            destinationList(this.listQuery).then(res => {
                setTimeout(() => {
                    this.listLoading = false;
                }, 300)
                this.targetList = res.data;
            });
        },
        refBtn(type) {
            this.fourthList();
        },
        handleResetSearch() {
            this.isCountry = false;
            this.listQuery = Object.assign({}, defaultListQuery);
            // this.listQuery.countryEsId = this.cityFirst;
            this.fourthList();
        },
        handleSearchList() {
            if (this.listQuery.countryEsId) {
                this.isCountry = true;
            } else {
                this.isCountry = false;
            }
            this.fourthList();
        },
        fourthAdd() {
            this.fourthResource = {
                id: null,
                countryEsId: null,
                cityEsId: null,
                status: 1,
                sort: null,
                updateTime: null,
                createTime: null,
                deleteYn: null,
            };
            this.isEdit = false;
            this.fourthVisible = true;
        },
        fourthDialogConfirm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isEdit) {
                        destinationUpdate(this.fourthResource).then(res => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                            this.fourthVisible = false;
                            this.fourthList();
                        });
                    } else {
                        destinationAdd(this.fourthResource).then(res => {
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            });
                            this.fourthVisible = false;
                            this.fourthList();
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        fourthEdite(index, row) {
            let newRow = row.city;
            newRow.country = row.country;
            this.fourthOptions = [];
            this.fourthOptions.push(newRow);
            this.fourthResource = {
                id: row.id,
                countryEsId: row.countryEsId,
                cityEsId:  row.cityEsId,
                status: row.status ? 1 : 0,
                sort: row.sort,
                updateTime: row.updateTime,
                createTime: row.createTime,
                deleteYn: row.deleteYn,
            };
            this.isEdit = true;
            this.fourthVisible = true;
        },
        fourthDelete(index, row) {
            this.$confirm('删除后该目的地会被清除，你还要继续吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                destinationDelete(row.id).then(response => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.fourthList();
                });
            });
        },
        handleSort() {
            const el = this.$el.querySelector('.el-table__body-wrapper tbody');
            this.sortShow = Sortable.create(el, {
                onEnd: (event) => {
                    const { oldIndex, newIndex } = event;
                    this.rowDrop(oldIndex, newIndex);
                }
            })
            this.isOneS = true;
        },
        handleSortC() {
            this.isOneS = false;
            this.sortShow.destroy();
            this.fourthList();
        },
        handleSortS() {
            this.sortBoList = [];
            this.targetList.forEach(item => {
                this.sortBoList.push(item.id)
            })
            this.$confirm('排序发生改变 确认是否提交?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                destinationSort({idList: this.sortBoList}).then(res => {
                    this.isOneS = false;
                    this.sortShow.destroy();
                    this.fourthList();
                    this.$message({
                        type: 'success',
                        message: '排序成功!'
                    });
                });
            });
        },
    }
}
</script>

<style lang="scss">
.btn-list {
    cursor: pointer;
}
</style>
